﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using dotNails.CodeGen.Util;
using dotNails.CodeGen.Models;

namespace dotNails.UI {
	/// <summary>
	/// Interaction logic for ResultClassSelector.xaml
	/// </summary>
	public partial class ResultClassSelector : UserControl {
		public DbmlData DbmlData { get; set; }
		public event ResultClassSavedHandler ResultClassSaved;
		public delegate void ResultClassSavedHandler(object sender, string resultClass, string procedureName);
		protected string _procedureName = string.Empty;
		protected string _currentResultClass = string.Empty; 
		
		public ResultClassSelector() {
			InitializeComponent();
		}

		public void LoadData(string procedureName, string currentResultClass) {
			_procedureName = procedureName;
			_currentResultClass = currentResultClass;
			ProcedureName.Text = _procedureName;
			ResultClasses.ItemsSource = DbmlData.DB.Tables;
			
			ResultClasses.SelectedIndex = -1;
			// Pre-select the combobox if a result class has already been selected
			foreach (dotNails.CodeGen.Models.Table table in ResultClasses.Items) {
				if (table.Type.Name == _currentResultClass) {
					ResultClasses.SelectedItem = table;
				}
			}
		}

		private void btnSave_Click(object sender, RoutedEventArgs e) {
			try {
				dotNails.CodeGen.Models.Table selectedResult = (dotNails.CodeGen.Models.Table)ResultClasses.SelectedItem;
				string resultClass = string.Empty;

				if (selectedResult != null) {
					 resultClass = selectedResult.Type.Name;
				}

				_currentResultClass = resultClass;
				
				// TODO: Make sure the selected type matches the resultset coming back from the proc

				if (ResultClassSaved != null) {
					ResultClassSaved(this, resultClass, _procedureName);
					Visibility = Visibility.Collapsed;
				}
				else {
					//DisplayTestResult("Say something?", false);
				}
			}
			catch (Exception ex) {
				LogUtil.EventLogMessage(ex.Message, ex.InnerException, ex.StackTrace);
			}
		}

		private void btnCancel_Click(object sender, RoutedEventArgs e) {
			Visibility = Visibility.Collapsed;
		}

	}
}
